import { createContext, useContext, useState } from 'react';
import { Snackbar, Alert } from '@mui/material';

const MessageContext = createContext();

const MessageProvider = ({ children }) => {
  const [snackbar, setSnackbar] = useState({
    open: false,
    message: '',
    severity: 'error',
    vertical: 'top',
    horizontal: 'right',
  });

  const showMessage = (message, options = {}) => {
    const { severity = 'error', duration = 6000, vertical = 'top', horizontal = 'right' } = options;
    const validSeverities = ['error', 'success', 'warning', 'info'];
    const normalizedSeverity = validSeverities.includes(severity) ? severity : 'error';

    setSnackbar({
      open: true,
      message,
      severity: normalizedSeverity,
      vertical,
      horizontal,
      duration,
    });
  };

  const showError = (error, options = {}) => {
    let errorMessage = '';
    
    if (!error) {
      errorMessage = 'An unknown error occurred';
    }
  
    else if (typeof error === 'string') {
      errorMessage = error;
    }
    
    else if (typeof error === 'object') {
     
      const baseMessage = error.message || 'An error occurred';
     
      if (error.errors && typeof error.errors === 'object') {
        const errorEntries = Object.entries(error.errors);
        if (errorEntries.length > 0 && errorEntries.every(([_, value]) => Array.isArray(value))) {
         
          const formattedErrors = errorEntries
            .map(([field, messages]) => {
              const fieldLabel = field.charAt(0).toUpperCase() + field.slice(1);
              return `${fieldLabel}: ${messages.join(', ')}`;
            })
            .join('\n'); 
          errorMessage = `${baseMessage}\n${formattedErrors}`;
        } else {
          errorMessage = baseMessage; 
        }
      } else {
        errorMessage = baseMessage; 
      }
    }
  
    else {
      errorMessage = 'An unknown error occurred';
    }

    showMessage(errorMessage, { ...options, severity: 'error' });
  };

  const showSuccess = (successMessage, options = {}) => showMessage(successMessage, { ...options, severity: 'success' });

  const closeMessage = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setSnackbar((prev) => ({ ...prev, open: false }));
  };

  const value = {
    showError,
    showSuccess,
    closeMessage,
  };

  return (
    <MessageContext.Provider value={value}>
      {children}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={snackbar.duration || 6000}
        onClose={closeMessage}
        anchorOrigin={{ vertical: snackbar.vertical, horizontal: snackbar.horizontal }}
      >
        <Alert
          onClose={closeMessage}
          severity={snackbar.severity}
          variant="filled"
          sx={{ 
            width: '100%', 
            whiteSpace: 'pre-line', 
          }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </MessageContext.Provider>
  );
};

const useMessage = () => {
  const context = useContext(MessageContext);
  if (!context) {
    throw new Error('useMessage must be used within a MessageProvider');
  }
  return context;
};

export { MessageProvider, useMessage };